<?php


namespace App\Dao;

use App\Model\Casts\TimeCasts;
use App\Model\ImchatMessageLog;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Collection;

class ImChatMessageLogDao extends AbstractDao
{
    /**
     * @param array $where
     * @return Builder
     */
    public function where(array $where): Builder
    {
        $query = ImchatMessageLog::query();
        foreach ($where as $key => $value) {
            $query->where($key, $value);
        }
        return $query;
    }

    /**
     * 获取聊天历史
     * @param $data
     * @return Builder[]|Collection
     */
    public function getMessageLog($data)
    {
        $where = [
            ['id', '<', $data['last_history_id']],
            ['send_user', '=', $data['send_user']],
            ['receive_user', '=', $data['receive_user']],
        ];

        $orwhere = [
            ['receive_user', '=', $data['send_user']],
            ['send_user', '=', $data['receive_user']],
        ];

        if (isset($data['cooperative_employer_user'])){
            array_push($where,['cooperative_employer_user','=',$data['cooperative_employer_user']]);
            array_push($orwhere,['cooperative_employer_user','=',$data['cooperative_employer_user']]);
        }

       return ImchatMessageLog::query()
           ->select('id','imchat_id','message','status','created_at','send_user')
           ->where($where)
           ->orWhere(function ($query) use ($orwhere){
               $query->where($orwhere);
           })->withCasts(['created_at' => TimeCasts::class])
           ->orderBy('id', 'desc')->limit($data['per_page'])->get();
    }

    /**
     * 更新
     * @param $ids
     * @param $status
     * @return int
     */
    public function updateStatus($ids,$status)
    {
       return ImchatMessageLog::query()
               ->whereIn('id',$ids)
               ->update(['status'=>$status]);
    }

    /**
     * 获取最后聊天信息的ID
     * @param $chatId
     * @return string
     */
    public function getLastRowByImchatID($chatId)
    {
        return $this->where(['imchat_id'=>$chatId])->orderBy('id','DESC')->first();
    }


}